﻿/// <reference path="../ExtJS/adapter/ext/ext-base.js" />
/// <reference path="../ExtJS/ext-all.js" />
/// <reference path="../ExtJS/ExtJSextend.js" />
/// <reference path="tabCommon.js" />

var grid = null;
var reader = new Ext.data.JsonReader({
    idProperty: 'ID',
    fields: [
        { name: 'DepartmentName', type: 'string' },
        { name: 'ID', type: 'string' },
        { name: 'UserName', type: 'string' },
        { name: 'DepartmentID', type: 'string' },
        { name: 'FullName', type: 'string' },
        { name: 'DisplayName', type: 'string' },
        { name: 'cCode', type: 'string' }
    ]
});
var gridStore = new Ext.data.GroupingStore({
    reader: reader,
    data: [],
    pruneModifiedRecords: true, //重新加载数据时清空以前修改：重要
    sortInfo: { field: 'DisplayName', direction: 'ASC' },
    groupField: 'DepartmentName'
});

//生成表格数据并加载数据
function loadData() {
    //获取授权数据
    tabAjaxPost('/Ajax/ChartCodeList?ChartID=' + ChartInfo.cid, function (json) {
        if (json.code == 1) {
            //json.data

            var dataCount = json.data.length;
            var depCount = _depStore.getCount();
            var userDataCount = _userStore.getCount();

            //循环部门是只为先按部门排序
            var grid_data = [];
            for (var i = 0; i < depCount; i++) { //循环部门
                for (var m = 0; m < userDataCount; m++) { //循环用户
                    var obj = _userStore.getAt(m).json;

                    if (_depStore.getAt(i).json.ID.toString().toLowerCase() == obj.DepartmentID.toString().toLowerCase()) {
                        obj["DepartmentName"] = GetDepartmentName(obj.DepartmentID);
                        obj["cCode"] = '0';

                        //循环授权列表
                        for (var n = 0; n < dataCount; n++) {
                            if (obj.ID.toString().toLowerCase() == json.data[n].UserID.toString().toLowerCase())
                                obj["cCode"] = json.data[n].Code;
                        }

                        grid_data.push(obj);
                    }
                }
            }
            gridStore.loadData(grid_data);

        } else {
            errorMessage(json.msg);
        }
    });
}

Ext.onReady(function () {

    //表格与布局
    var grid = new Ext.grid.EditorGridPanel({
        ds: gridStore,
        columns: [
            new Ext.grid.RowNumberer(),
            { header: '部门名称', width: 180, dataIndex: 'DepartmentName', sortable: true, align: 'center' },
            { header: '用户标识', width: 260, dataIndex: 'ID', sortable: true, align: 'center', hidden: true },
            { header: '用户名', width: 150, dataIndex: 'UserName', sortable: true, align: 'center' },
            { header: '部门标识', width: 260, dataIndex: 'DepartmentID', sortable: true, align: 'center', hidden: true },
            { header: '用户姓名', width: 150, dataIndex: 'FullName', sortable: true, align: 'center' },
            { header: '用户显示名称', width: 150, dataIndex: 'DisplayName', sortable: true, align: 'center', hidden: true },
            {
                header: '授权码', width: 150, dataIndex: 'cCode', sortable: true, align: 'center',
                renderer: function (value, metaData, record, rowIndex, colIndex, store) {
                    var codeCount = codeStore.getCount();
                    for (var i = 0; i < codeCount; i++) {
                        if (codeStore.getAt(i).json.ID.toString().toLowerCase() == value.toString().toLowerCase())
                            return codeStore.getAt(i).json.Name;
                    }
                    return "未知";
                },
                editor: new Ext.form.ComboBox({
                    triggerAction: 'all',
                    store: codeStore,
                    displayField: 'Name',
                    valueField: 'ID',
                    mode: 'local'
                })
            }
        ],
        view: new Ext.grid.GroupingView({
            firceFit: true,
            deferEmptyText: false,
            emptyText: '暂无用户数据可供授权！',
            getRowClass: function (record, index) {
                if (!(index % 2)) {
                    return 'x-grid3-row';
                } else {
                    return 'x-grid3-row-alt';
                }
            },
            showGroupName: false,
            enableNoGroups: false,
            enableGroupingMenu: true,
            hideGroupedColumn: false
        }),
        clicksToEdit: 1
    });

    //视图内容与布局
    var _center = new Ext.Panel({
        region: 'center',
        layout: 'fit',
        items: [grid],
        tbar: [{
            text: '提交',
            iconCls: 'icons-base-accept',
            handler: function () {
                saveData();
            }
        }, {
            text: '刷新',
            iconCls: 'icons-chart-search',
            handler: function () {
                loadData();
            }
        }]
    });
    var _view = new Ext.Viewport({
        layout: 'border',
        items: [_center]
    });



    //加载部门与用户
    _depLoadData();
    _userLoadData();

    //加载表格数据
    loadData();

});

//保存表格编辑的结果
function saveData()
{
    var mr = gridStore.getModifiedRecords();
    if (mr.length == 0)
        errorMessage("没有修改任何数据，不需要提交！");

    var res = "";

    var mrCount = mr.length;
    for (var i = 0; i < mrCount; i++) {
        res += "," + '{ID:"' + mr[i].json.ID + '",Code:' + mr[i].data.cCode + '}'; //json为原数据，data为修改后数据
    }

    res = "[" + res.substr(1) + "]";

    tabAjaxPostData('/Ajax/ChartCodeUpdate', { ChartId: ChartInfo.cid, UpdateCode: res }, function (json) {
        if (json.code == 1) {
            loadData();
        } else {
            errorMessage(json.msg);
        }
    });
}
